package com.spring.cloud.examples.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 使用Ribbon方式
 * 查询Eureka注册中心的服务
 */
@RestController
@RequestMapping("/ribbonQueryEurekaService")
public class RibbonQueryEurekaServiceController {

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/server_info/port")
    @ResponseBody
    public String queryPort() {
        String result = restTemplate.getForObject("http://spring-cloud-eureka-service/server_info/port",String.class);
        return "Ribbon方式调用 服务端返回:"+result;
    }

    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("/serviceurl")
    public Map<String, List<ServiceInstance>> serviceUrl() {
        Map<String, List<ServiceInstance>> msl = new HashMap<>();
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            List<ServiceInstance> sis = discoveryClient.getInstances(service);
            msl.put(service, sis);
        }
        return msl;
    }

}
